package circular

import (
	"errors"
)

const testVersion = 4

type Buffer struct {
	header int
	end    int
	length int
	count  int
	b      []byte
}

func NewBuffer(size int) *Buffer {

	b := Buffer{0, 0, size, 0, make([]byte, size)}
	return &b
}

func (b *Buffer) ReadByte() (r byte, e error) {
	if b.count == 0 || b.length == 0 {
		e = errors.New("no data")
		return
	}

	b.count--
	r = b.b[b.header]
	b.header = (b.header + 1) % b.length
	return
}

func (b *Buffer) WriteByte(c byte) error {
	if b.count == b.length {
		return errors.New("full")
	}

	b.count++
	b.b[b.end] = c
	b.end = (b.end + 1) % b.length
	return nil
}

func (b *Buffer) Overwrite(c byte) {
	if b.count == b.length {
		b.b[b.header] = c
		b.header = (b.header + 1) % b.length
	} else {
		b.WriteByte(c)
	}
}

func (b *Buffer) Reset() {
	b.header = 0
	b.end = 0
	b.count = 0
	b.b = make([]byte, b.length)
}
